<template>
  <el-dialog
    title="选择养护记录"
    :visible.sync="visible"
    width="70%"
    :before-close="handleCancel"
    destroy-on-close
    class="dialog-form"
    >
        <el-form  :inline="true" size="medium">  
            <el-form-item label="养护日期">
                <el-date-picker
                    v-model="time"
                    type="daterange"
                    value-format="yyyy-MM-dd "
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <BaseButton @click="handleFilter">查询</BaseButton>
                <BaseButton type="second" @click="resetConditions()">重置</BaseButton>
            </el-form-item>
        </el-form>
        <div class="tips">
            <i class="el-icon-info info-icon"></i>
            <span>已选择
                <span class="num">{{ selectLength }}</span>
                条养护记录
                <span v-if="startDateAndEndDate[0]">，养护日期范围：{{ startDateAndEndDate[0] }} ~ {{ startDateAndEndDate[1] }}</span>
            </span>
        </div>
        <div class="table-warp">
            <div class="check-all">
                <el-checkbox v-model="checked" @change="checkAll"></el-checkbox>
            </div>
            <BaseTable 
            slot="table"
            ref="table" 
            class="table"  
            :data="pageList" 
            :columns="columns"
            highlight-current-row 
            height="calc(100% - 73px)" 
            @sort-change="handleSortChange"
            >
                <template #code="{ scope: { row} }">
                    <BaseButton type="text" @click="handleDetail(row)">  {{ row.recordCode }}</BaseButton>
                </template>
                <template #select="{ scope: { row} }">
                    <el-checkbox v-model="row.checked"></el-checkbox>
                </template>
                <template #type="{ scope: { row} }">
                    {{ row.type | value2Name(types) }}
                </template>
                <template #msStatus="{ scope: { row} }">
                    <StateTag  :id="row.msStatus" type="jiliang"></StateTag>
                </template>
            </BaseTable>
            <Pagination
                clas="pagination"
                :current-page.sync="page.pageNo"
                :page-size.sync="page.pageSize"
                :total="page.total"
                @size-change="getList"
                @current-change="getList"
            />
            </div>
            <div slot="footer" class="dialog-footer">
                <BaseButton type="second" :throttle-time="200" @click="handleCancel">取 消</BaseButton>
                <BaseButton @click="handelConfirm">确 定</BaseButton>
            </div>
    </el-dialog>
</template>
<script>
import { MetrologicalStatusOptions } from '@/views/maintenance-decision/constants'
import { value2Name } from '@/filters'
import StateTag from '../components/StateTag.vue'
import { MsMaintrecordModel } from '@/models'
export default {
    components: {
        StateTag
    },
    filters: {
        value2Name
    },
    props: {
        queryData: {
            type: Object,
            default: () => {}
        },
        delDevInDetail: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            model: new MsMaintrecordModel(),
            visible: false,
            page: {
                pageNo: 1,
                pageSize: 10,
                total: 0
            },
            list: [], // 全量list
            pageList: [], // 当前页面的list
            columns: [
                {
                    
                    slot: 'select',
                    attrs: {
                        label: '',
                        prop: 'cehcked',
                        aling: 'left',
                        width: 60,
                    }
                },
                {
                    slot: 'code',
                    attrs: {
                        label: '养护记录编号',
                        prop: 'code',
                        width: 150,
                    }
                },
                {
                    attrs: {
                        label: '养护日期',
                        prop: 'maintDate',
                        'show-overflow-tooltip': true,
                        sortable: 'custom',
                    }
                },
                {
                    slot: 'type',
                    attrs: {
                        label: '类型',
                        prop: 'type',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '施工单位',
                        prop: 'constructionUnitName',
                        'show-overflow-tooltip': true
                    }
                },
                
                {
                    attrs: {
                        label: '现场管理',
                        prop: 'managementUnitName',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '工作内容',
                        prop: 'workContent',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'msStatus',
                    attrs: {
                        label: '计量状态',
                        prop: 'msStatus',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '更新人',
                        prop: 'operatorName',
                    }
                },
                {
                    attrs: {
                        label: '更新时间',
                        prop: 'updateTime',
                        sortable: 'custom',
                    }
                },
            ],
            metrologicalStatusOptions: MetrologicalStatusOptions, // 计量状态
            time: [],
            checked: false,
            listIds: [], // 已存在在父级页面的id
            query: {}
        }
    },   
    computed: {
        // 页码数组
        pageArr() {
            const num = Math.ceil(this.list.length / this.page.pageSize)
            const arr = []
            for (let i = 1; i <= num; i++) {
                arr.push(i)
            }
            return arr
        },
        types() {
            return this.$store.state.types.maintenanceApplyTypes || []
        },
        selectLength() {
            return this.list.filter(el => el.checked).map(el => el.id).length || 0
        },
        startDateAndEndDate() {
            const dateList = this.list.filter(el => el.checked).map(el => el.maintDate)
            let start = ''
            let end = ''
            if (dateList.length && dateList.length === 1) {
                start = dateList[0]
                end = dateList[0]
            } else if (dateList.length && dateList.length >= 2) {
                const {minDate, maxDate} = this.findMinAndMaxDates(dateList)
                start = minDate
                end = maxDate
            } else {
                start = ''
                end = ''
            }
            return [start, end]
        }
    },
    watch: {
        queryData: {
            immediate: true,
            deep: true,
            handler() {
                this.query = {...this.queryData}
                this.time = [this.query.startDate, this.query.endDate] 
            }
        },
        time: {
            deep: true,
            immediate: true,
            handler(val) {
                if (val && val.length) {
                    this.query.startDate = val[0]
                    this.query.endDate = val[1]
                } else {
                    this.query.startDate = ''
                    this.query.endDate = ''
                }
            }
        },
        visible: {
            immediate: true,
            handler(val) {
                if (val) {
                    setTimeout(() => {
                        this.getList()
                    }, 100)
                }
            }
        },
        // 设备未选提示信息不显示
        list: {
            immediate: true,
            deep: true,
            handler(val) {
                this.page.total = this.list.length
            }
        },
    },
    created() {
        this.getTypes()
    },
    methods: {
        // 查看养护记录详情查看养护记录详情
        handleDetail(row) {
            const targetUrl = this.$router.resolve({
                name: 'MaintenanceRecordManagementDetail',
                query: {
                    id: row.id,
                }
            }).href
            // 使用window.open在新标签页中打开该URL
            window.open(targetUrl, '_blank')
        },
        findMinAndMaxDates(dates) {
            let minDate = new Date(dates[0])
            let maxDate = new Date(dates[0])
 
            for (let i = 1; i < dates.length; i++) {
                const date = new Date(dates[i])
                if (date < minDate) {
                    minDate = date
                } else if (date > maxDate) {
                    maxDate = date
                }
            }
 
            return { 
                minDate: this.$dayjs(minDate).format('YYYY-MM-DD'), 
                maxDate: this.$dayjs(maxDate).format('YYYY-MM-DD')
            }
        },
        getTypes() {
            this.$store.dispatch('types/query', 'maintenanceApplyTypes')
        },
        resetConditions() {
            this.time = []
            this.query.startDate = ''
            this.query.endDate = ''
            this.handleFilter()
        },
        handleFilter() {
            this.pageNo = 1
            this.getList()
        },
        // 获取列表
        getList() {
            this.model.getList({...this.query}).then(
                res => {
                    if (res) {
                        this.list = [...res].filter(el => this.listIds.indexOf(el.id) === -1).map(el => {
                            return {
                                ...el,
                                checked: false
                            }
                        }).concat([...this.delDevInDetail])
                        this.classPageList()
                    }
                }
            )
        },
        // 取消
        handleCancel() {
            this.visible = false
        },
        // 确定
        handelConfirm() {
            this.visible = false
            const selectList = this.list.filter(el => el.checked)
            this.$emit('selectChange', selectList)
        },
        // 分页操作
        classPageList() {
            const pageSize = this.page.pageSize
            this.pageList = []
            const pageNo = this.page.pageNo
            const endIndext = pageNo * pageSize // 10  slice函数左闭右开
            const startIndex = endIndext - 1 - (pageSize - 1) // 0
            const list = [...this.list]
            this.pageList = list.slice(startIndex, endIndext)
        },
        // 排序, ascending升序 descending降序
        handleSortChange({ column, prop, order }) {  
            if (prop === 'updateTime') {
                if (order === 'ascending') {  
                    this.sortList('updateTime', 'ascending')
                    this.classPageList()
                } else {
                    // 默认排序
                    this.sortList('updateTime', 'descending')
                    this.classPageList()
                }
            }
            if (prop === 'maintDate') {
                if (order === 'ascending') {  
                    this.sortList('maintDate', 'ascending')
                    this.classPageList()
                } else {
                    this.sortList('maintDate', 'descending')
                    this.classPageList()
                }
            }
        },
        sortList(key, order) {
            this.list.sort(function(a, b) {
                var keyA = new Date(a[key])
                var keyB = new Date(b[key])
                // 正序排序
                if (order === 'ascending') {
                    if (keyA > keyB) return 1
                    if (keyA < keyB) return -1
                } else if (order === 'descending') {
                    if (keyA > keyB) return -1
                    if (keyA < keyB) return 1
                } else {
                    return 0
                }
                return 0
            })
        },
        // 全选
        checkAll(val) {
            this.list = this.list.map(el => {
                return {
                    ...el,
                    checked: val
                }
            })
            this.classPageList()
        },
    }
}
</script>
<style scoped lang="scss">
.table-warp{
  
    position: relative;
    .table{
        width:100%;
        min-height: 400px;
    }
    .check-all{
        width:60px;
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        margin-top: 14px;
    }
    .pagination{
        text-align: right;
        margin-right: 20px;
    }
}
.tips{
    margin:8px;
    background-color:rgba(4, 97, 255, 0.1) ;
    border: 1px solid rgba(4, 97, 255, 0.2);
    padding: 10px ;
    border-radius: 4px;
    .num,.info-icon{
        color: #409EFF;
    }
  }

</style>
